package com.budweiser.budweisermain.service.impl;

import com.budweiser.budweisermain.repository.NavMenuRepository;
import com.budweiser.budweisermain.service.NavMenuService;
import com.budweiser.commons.utils.MenuJsonUtil;
import com.budweiser.model.system.menu.NavMenu;
import com.budweiser.model.system.menu.enums.MenuType;
import com.budweiser.model.system.menu.result.GroupMenu;
import com.budweiser.model.system.menu.result.Item;
import com.budweiser.model.system.menu.result.Submenu;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.xb.xsdschema.SimpleDerivationSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.budweiser.commons.utils.MenuJsonUtil.togetherGroupMenu;

@Slf4j
@Service
public class NavMenuServiceImpl implements NavMenuService {

    @Autowired
    private NavMenuRepository navMenuRepository;

    @Override
    public List<GroupMenu> findAllNavMenu() {
        /*先找第一层菜单*/
        List<NavMenu> navMenuList = navMenuRepository.findByParentId(0);
        Map<String, GroupMenu> navGroupMap =  togetherGroupMenu(navMenuList);
        /*以下为需要优化的代码，三层for循环，！！！！！！！！！！！！！！！！！！！！！！！*/
        for (NavMenu navMenu : navMenuList) {
            /*每次根据顶级菜单的id去向下寻找子菜单*/
            List<NavMenu> midMenuList = navMenuRepository.findByParentId(Integer.valueOf(navMenu.getMenuId()));
            /*在map中定位该顶级菜单*/
            for (Submenu submenu : navGroupMap.get(navMenu.getGroupTitle()).getSubmenus()) {
                if (submenu.getTitle().equals(navMenu.getMenuName())) {
                    /*将childList转换为itemList*/
                    List<Item> itemList = new ArrayList<>();
                    for (NavMenu child : midMenuList) {
                        Item item = new Item();
                        item.setIcon(child.getMenuCSS());
                        item.setIndex(child.getMenuRouteLink());
                        item.setTitle(child.getMenuName());
                        itemList.add(item);
                    }
                    submenu.setItems(itemList);
                }
            }
        }
        /*最后将map转为换list*/
        List<GroupMenu> groupMenuList = new ArrayList<>();
        for (Map.Entry<String, GroupMenu> menuEntry : navGroupMap.entrySet()) {
            groupMenuList.add(menuEntry.getValue());
        }
        return groupMenuList;
    }

    @Override
    public List<NavMenu> findMenuByType(MenuType menuType) {
        return null;
    }

    @Override
    public List<NavMenu> findMenuByParentId(int parentId) {
        return null;
    }
}
